package com.zwan.oam_rtc.service;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zwan.oam_rtc.bean.NumberAnalysis;
import com.zwan.oam_rtc.bean.OamSettings;
import com.zwan.oam_rtc.bean.entity.FSMStatus;
import com.zwan.oam_rtc.bean.entity.UserFSM;
import com.zwan.oam_rtc.constants.Const;
import com.zwan.oam_rtc.utils.NumberPoolParser;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class NumberAnalysisService {
    @Autowired
    OamSettings oamSettings;
    private NumberPoolParser numberPoolParser;

    @PostConstruct
    public void init() {
        try {
            this.numberPoolParser = new NumberPoolParser(oamSettings.getTrunkCallingPool());
        } catch (IllegalArgumentException e) {
            log.error("Error parsing number pool: {}", e.getMessage());
        }   
    }

    public String getTypeString(short type) {
        if (type == Const.partcipation_type_sip_volte) {
            return "trunk";
        } else if (type == Const.partcipation_type_sip_phone) {
            return "device";
        } else {
            log.error("getTypeString error: " + type);
            return null;
        }
    }

    public short getTypeShort(String type) {
        if (type.equals("device")) {
            return Const.partcipation_type_sip_phone;
        } else if (type.equals("trunk")) {
            return Const.partcipation_type_sip_volte;
        } else {
            log.error("getTypeShort error: " + type);
            return Const.partcipation_type_none;
        }
    }

    public boolean analysis(UserFSM userFSM) {
        if (userFSM == null) {
            log.error("analysis parameter error");
            return false;
        }

        String inbound_type = getTypeString(userFSM.getType());
        if (inbound_type == null) {
            return false;
        }

        // 查找号码分析子
        NumberAnalysis result = null;
        for (NumberAnalysis n : oamSettings.getNumberanalysis()) {
            boolean type_match = false;
            boolean calling_match = false;
            boolean called_match = false;

            if (n.getInboundtype().equals(inbound_type) || n.getInboundtype().equals("*")) {
                type_match = true;
            }

            if (n.getInboundcallingnumber().equals(userFSM.getCaller()) || n.getInboundcallingnumber().equals("*")) {
                calling_match = true;
            }

            if (n.getInboundcallednumber().equals(userFSM.getCallee()) || n.getInboundcallednumber().equals("*")) {
                called_match = true;
            }

            if (type_match && calling_match && called_match) {
                log.info("number analysis found: " + n.getInboundtype() + " " + n.getInboundcallingnumber() + " "
                        + n.getInboundcallednumber());
                result = n;
                break;
            }
        }

        if (result == null) {
            log.error("number analysis not found: " + userFSM.getType() + " " + userFSM.getCaller() + " "
                    + userFSM.getCallee());
            return false;
        }

        // 应用号码分析子
        if (result.getOutboundtype().equals("trunk")) {

            // 中继主叫，从号码池中选择
            if(result.getOutboundtrunkcalling().equals("*")) {
                //取源主叫
                userFSM.setForward_calling(userFSM.getCaller());
                userFSM.setIs_pool_number(false);
            }else if(result.getOutboundtrunkcalling().equals("pool")) {
                //从号码池中取
                try{
                    userFSM.setForward_calling(numberPoolParser.getNumber());
                    userFSM.setIs_pool_number(true);
                }catch (Exception e) {
                    log.error("获得中继号码失败" + e);
                    userFSM.setStatus(FSMStatus.ERROR);
                }
            }

            // 中继被叫，从配置中读取
            if (result.getOutboundcallednumber().equals("*")) {
                if (userFSM.getCallee().startsWith("+86")) { // 中继被叫，必须加+86呼出
                    userFSM.setForward_called(userFSM.getCallee());
                } else {
                    userFSM.setForward_called("+86" + userFSM.getCallee());
                }
            } else {
                userFSM.setForward_called(result.getOutboundcallednumber());
            }

            userFSM.setForward_ip(result.getOutboundtrunkip());
            userFSM.setForward_port(result.getOutboundtrunkport());
            userFSM.setForward_type(getTypeShort(result.getOutboundtype()));
            userFSM.setForward_local_media_public_ip(result.getOutboundtrunklocalpublicmediaip());
            // log.info("setForward_local_media_public_ip:" + userFSM.getForward_local_media_public_ip());
        } else if (result.getOutboundtype().equals("device")) {

            // 终端主叫，来自于原始主叫
            userFSM.setForward_calling(userFSM.getCaller());

            // 终端被叫，从配置中读取
            if (result.getOutboundcallednumber().equals("*")) {
                userFSM.setForward_called(userFSM.getCallee());
            } else {
                userFSM.setForward_called(result.getOutboundcallednumber());
            }

            userFSM.setForward_type(getTypeShort(result.getOutboundtype()));
        }

        return true;
    }

    public void returnNumber(UserFSM userFSM) {
        if (userFSM.getForward_type() == Const.partcipation_type_sip_volte && userFSM.getIs_pool_number()) {
            numberPoolParser.returnNumber(userFSM.getForward_calling());
        }
    }
}
